<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use Alipay\EasySDK\Kernel\Util\Signer;
use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\forest\Member;
use app\common\model\forest\Order as ForestOrder;
use app\common\model\Goods;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\product\Member as ProductMember;
use app\common\model\product\Order as ProductOrder;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Db;
use think\Log;

/**
 * 回调接口
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 支付宝回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $signer = new Signer();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $signer->verifyParams($post, $alipayrsaPublicKey);
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'GO') {
                    $order =  Order::get(['sn' => $out_trade_no]);
                    if ($order && $order->status == '0') {
                        $user = User::get($order->user_id);
                        //首次下单获取19GR积分
                        $num = MoneyLog::where('source_type', 100)->where('user_id', $user->id)->count();
                        if (!$num) {
                            MoneyLog::income($user->id, 19, 2, 100, $out_trade_no);
                        }
                        //普通商品购买获得等值得GS积分
                        ScoreLog::income($order->user_id, $order->pay_money, 2, 501, $out_trade_no);

                        //糖友会员
                        if ($user->group_id == 0) {
                            $count = OrderGoods::where('order_id', $order->id)->where('sugar_member', 1)->count();
                            if ($count > 0) {
                                $user->group_id = 1;
                            }
                        }
                        $order->save(['status' => '1', 'paytime' => time(), 'transaction_id' => $trade_no], ['sn' => $out_trade_no]);
                        $user->total_money = $user->total_money + $order->pay_money;
                        $user->save();
                    }
                }
                if ($str == 'PO') {
                    $order =  ProductOrder::get(['sn' => $out_trade_no]);
                    if ($order && $order->status == '0') {
                        $user = User::get($order->user_id);
                        if ($user->leaf_level < $order->goods_id) {
                            $user->leaf_level = $order->goods_id;
                            if ($order->goods_id == 1) {
                                ScoreLog::income($order->user_id, 1000, 2, 600, $out_trade_no);
                            }
                        }
                        $order->save(['status' => '1', 'transaction_id' => $trade_no, 'paytime' => time()]);
                        User::leafcommission($order);
                        if ($user->is_first == 0) {
                            $user->fee = bcmul($order->price, 0.1, 2);
                            $user->month = 10;
                            $user->is_first = 1;
                            $puser = User::get($user->pid);
                            if ($puser && $puser->month > 0) {
                                $puser->month = ceil($puser->month / 2);
                                $puser->save();
                            }
                        }
                        $user->total_money = $user->total_money + $order->price;
                        $user->save();
                    }
                    //检查用户产品会员是否升级
                    User::nextlevel($order->user_id);
                }
                if ($str == 'FO') {
                    $order =  ForestOrder::get(['sn' => $out_trade_no]);
                    if ($order && $order->status == '0') {
                        $user = User::get($order->user_id);
                        $forest_code = User::where('validitytime', '>', time())->order('forest_code desc')->value('forest_code');
                        if (!$forest_code) {
                            $user->forest_code = '30001';
                        } else {
                            $user->forest_code = (int) $forest_code + 1;
                        }
                        if ($user->forest_level < $order->goods_id || $user->validitytime < time()) {
                            $time = strtotime("+2 year");
                            $user->forest_level = $order->goods_id;
                            $user->validitytime = $time;
                            $member = Member::get($order->goods_id);
                            Log::write('记录日志：' . json_encode($post), 'err');
                            if ($order->plant == 0) {
                                ScoreLog::income($order->user_id, $member['price'], 2, 502, $out_trade_no);
                                $user->total_money = $user->total_money + $member['price'];
                            } else {
                                MoneyLog::income($order->user_id, $member['price'], 2, 601, $out_trade_no, 2);
                            }
                            $user->save();
                        }
                        $order->save(['status' => '1', 'transaction_id' => $trade_no, 'paytime' => time()]);
                    }
                }

                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }
    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data = '{"id":"fbeba5e3-639c-51b9-810f-5c8a3a28943b","create_time":"2023-03-27T14:23:29+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"dZ50MV0FA9NaX05KypweeaDJLaB5P8Dkeb+r0JUpGRtrWMN8ed2CKrTaRQvItjqtDTOY0W+Dq5z3Xa25uB2FFZuQZ4O0Qft4hOLzjfaSy7EVJhtabtLJiAgeknH5foHynDEeNgQIcNVg6neK+XLHiRNaOwt65VIzXJwq6jhVG60IFPTVNLxXl/EdlCtQqbg7ubjq/ANCZMcBIyvsyc9Rdymfi+nOs+3DACiivvYsze46inNM7rOUyR0V5XNd8dPDyaP0MCoWxM44aGtcLrsmmjf8UlmlG1qntgRrLyHlLMFn3vzaYW9bao0X0McM/EEEGCOWodt76jzKT8uCbxOiypmz0fxmmnMSKWqPFUtmwqeELBZzGc0JTUeAQvTqk7sRYC3MFNe3ZWgY+aQDqDclCSCHIOcHls3Ce/BgOb0im78dKB9j4rMx1KwJ7EUhQlAo1sJYd4eOz8iE9fBQ39Jjo5Teo3GXkEUMeVlZmUnDfTfL3Z/tjCNenpBcWEIz+ia6bVIVL5QFvC1NpsQMjX4k9OacKBG76MTZDcZy4JGcD2wlo4zoKR8GHDPsthCnLcd4LS0HmAkG+B556Xud0jV1F/k=","associated_data":"transaction","nonce":"NFrAseQRa3b5"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];

        $ciphertext = base64_decode($ciphertext);

        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {

            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'mS3jB3fF0tA3hD8xC7sD2eE5kS3lP8pC');
            // $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'WYa96C3GM2PLVt4opEhKwJdez59043qn');

            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);

            if ($orderData['trade_state'] == 'SUCCESS') {
                $out_trade_no = $orderData['out_trade_no']; //商户订单号
                $trade_no = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                $str = substr($out_trade_no, 0, 2);

                // 启动事务
                Db::startTrans();
                try {

                    if ($str == 'GO') {
                        $order =  Order::get(['sn' => $out_trade_no]);
                        if ($order && $order->status == '0') {
                            $user = User::get($order->user_id);
                            //首次下单获取19GR积分
                            $num = MoneyLog::where('source_type', 100)->where('user_id', $user->id)->count();
                            if (!$num) {
                                MoneyLog::income($user->id, 19, 2, 100, $out_trade_no);
                            }
                            //普通商品购买获得等值得GS积分
                            ScoreLog::income($order->user_id, $order->pay_money, 2, 501, $out_trade_no);
                            //糖友会员
                            if ($user->group_id == 0) {
                                $count = OrderGoods::where('order_id', $order->id)->where('sugar_member', 1)->count();
                                if ($count > 0) {
                                    $user->group_id = 1;
                                }
                            }
                            $order->save(['status' => '1', 'paytime' => time(), 'transaction_id' => $trade_no], ['sn' => $out_trade_no]);
                            $user->total_money = $user->total_money + $order->pay_money;
                            $user->save();
                        }
                    }
                    if ($str == 'PO') {
                        $order =  ProductOrder::get(['sn' => $out_trade_no]);
                        if ($order && $order->status == '0') {
                            $user = User::get($order->user_id);
                            if ($user->leaf_level < $order->goods_id) {
                                $user->leaf_level = $order->goods_id;
                                if ($order->goods_id == 1) {
                                    $member = ProductMember::get($order->goods_id);
                                    if ($user->leaf_level_time && $user->leaf_level_time > time()) {
                                        $user->leaf_level_time = $user->leaf_level_time + $member['day'] * 86400;
                                    } else {
                                        $user->leaf_level_time = strtotime("+{$member['day']} day");
                                    }
                                }
                                if ($order->goods_id == 2) {
                                    ScoreLog::income($order->user_id, 1000, 2, 600, $out_trade_no);
                                }
                            }
                            $order->save(['status' => '1', 'transaction_id' => $trade_no, 'paytime' => time()]);
                            User::leafcommission($order);
                            // if ($user->product_level < $order->goods_id) {
                            //     $user->product_level = $order->goods_id;
                            //     MoneyLog::income($order->user_id, $order->price, 2, 200, $out_trade_no, 1);
                            // }
                            // $product = new ProductOrder();
                            // $product->save(['status' => '1', 'transaction_id' => $trade_no, 'paytime' => time()], ['sn' => $out_trade_no]);
                        }
                        $user->total_money = $user->total_money + $order->price;
                        $user->save();
                        //检查用户产品会员是否升级
                        User::nextlevel($order->user_id);
                    }
                    if ($str == 'FO') {
                        $order =  ForestOrder::get(['sn' => $out_trade_no]);
                        if ($order && $order->status == '0') {
                            $user = User::get($order->user_id);
                            $forest_code = User::where('validitytime', '>', time())->order('forest_code desc')->value('forest_code');
                            if (!$forest_code) {
                                $user->forest_code = '30001';
                            } else {
                                $user->forest_code = (int) $forest_code + 1;
                            }
                            if ($user->forest_level < $order->goods_id || $user->validitytime < time()) {
                                $time = strtotime("+2 year");
                                $user->forest_level = $order->goods_id;
                                $user->validitytime = $time;
                                $member = Member::get($order->goods_id);
                                if ($order->plant == 0) {
                                    ScoreLog::income($order->user_id, $member['price'], 2, 502, $out_trade_no);
                                    $user->total_money = $user->total_money + $member['price'];
                                } else {
                                    MoneyLog::income($order->user_id, $member['price'], 2, 601, $out_trade_no, 2);
                                }
                                $user->save();
                            }
                            $forest = new ForestOrder();
                            $forest->save(['status' => '1', 'transaction_id' => $trade_no, 'paytime' => time()], ['sn' => $out_trade_no]);
                        }
                    }
                    //检查用户产品会员是否升级
                    // User::nextlevel($order->user_id);

                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
}
